package com.cloudfun.campusshare.util.tencent;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;

/**
 * @author linyangping
 */
@Slf4j
public class TencentSMSUtil {

    /**
     * 腾讯云控制台中的appid
     */
    private static final int APPID = 1400301296;

    /**
     * 腾讯云控制台中的appkey
     */
    private static final String APPKEY = "ee370a331360a102f6908dbaad980d49";

    /**
     * 腾讯云控制台中短信的签名，如可能调用多个签名则无需写成静态变量
     */
    private static final String SIGNATURE = "杭州甘道智能科技有限公司";

    /**
     * 腾讯云控制台中短信模板id
     */
    private static final Integer VERIFY = 513530;

    /**
     * 发送短信种类（0：普通短信；1：营销类短信），从控制台获取，默认为0
     */
    private static final int TYPE_NORMAL = 0;

    /**
     * 短信接收手机号国家，默认中国
     */
    private static final String NATION_CODE = "86";

    public static final int SUCCESS_CODE = 0;

    public static SmsSingleSenderResult sendSMSWithParams(String phoneNumber, int templateId, String[] params) throws HTTPException, IOException {

        SmsSingleSender ssender = new SmsSingleSender(APPID, APPKEY);

        // 签名参数未提供或者为空时，会使用默认签名发送短信
        SmsSingleSenderResult result = null;
        try {
            result = ssender.sendWithParam(NATION_CODE, phoneNumber, templateId, params, SIGNATURE, "", "");
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
        }
        if (result.result == SUCCESS_CODE) {
            log.info("{}发送成功，result is {}", phoneNumber,result);
        } else {
            log.error("{}发送失败，result is {}", phoneNumber,result);
        }
        return result;
    }

    public static SmsSingleSenderResult sendSMS(String phoneNumber, int templateId, String msg) throws HTTPException, IOException {

        SmsSingleSender ssender = new SmsSingleSender(APPID, APPKEY);
        if (templateId == VERIFY) {
            msg = "【" + SIGNATURE + "】您的验证码为" + msg + "，验证码的有效时长为5分钟，请勿泄露给他人，并进尽快完成验证";
        } else {
            msg = "【" + SIGNATURE + "】您的私钥解密验证码为" + msg + "，验证码有效时长为5分钟，请勿泄露给他人。请注意，私钥解密下载后将无法再次下载，请保管好私钥。";
        }
        SmsSingleSenderResult result = null;
        try {
            result = ssender.send(TYPE_NORMAL, NATION_CODE, phoneNumber, msg, "", "");
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
        }
        if (result.result == SUCCESS_CODE) {
            log.info("result is {}", result);
        } else {
            log.error("result is {}", result);
        }
        return result;
    }


    public static void main(String[] args) throws HTTPException, IOException {
        String[] params = {"20", "50"};
        TencentSMSUtil.sendSMSWithParams("17356681385", 965897, params);
    }

}
